import Taro, { Component } from '@tarojs/taro'
// import { View, Text, Label, Radio, RadioGroup, Button} from '@tarojs/components'
import {View, Text, Label,Radio, Button} from '@tarojs/components'
import './index.scss'

import Good from '../../components/subscribeSubmit/good'
import Info from '../../components/subscribeSubmit/info'
import Remark from '../../components/subscribeSubmit/remark'
import Footer from '../../components/subscribeSubmit/footer'
import Authorize from '../../components/authorize/authorize'
import ItemInput from '../../components/itemInput'

import { set as setGlobalData, get as getGlobalData } from '../../static/js/global_data'
import api from '../../service/api'
import base from '../../static/js/base'
import common from '../../service/common'

export default class Index extends Component {
    config = {
        navigationBarTitleText: '预约提交',
    }
    constructor() {
        super(...arguments)
        this.state = {
            userInfo: Taro.getStorageSync('userInfo') || null,
            N_ApptType: 2, //预约类型 1 电话预约 2 网络预约 3 其他
            N_OpId: 0, //操作人编号
            N_Id: 0, // 预约编号(添加为0， 编辑传编号)
            C_AddDate: '', // 添加时间
            N_StaffId: 0, //预约员工号
            D_StartDate: '',
        //     N_RoomId: "", //房间编号（ 先传0， 以后需要再扩展）
        //     C_RoomName: "", //房间名（ 可不传， 以后需要再扩展）
            submitState: false,
            industry: getGlobalData('industry'), 
            ItemInputData: []
        }
    }
  // authorize获取作用域
    getIsLogin(obj){
        if(obj){
            if(obj.C_MB_NO){ 
                this.loadData(obj)
            }else{
                obj.isLogin(() => {
                    this.loadData()
                })
            }
        }	
    }
    componentWillMount(obj) { 
        this.getIsLogin(obj)
    }
    componentDidShow(){
        let subscribeProject = getGlobalData('subscribeProject') ? getGlobalData('subscribeProject') : null
        this.setState({
            subscribeProject: subscribeProject
        })
        if(this.state.refrech){
            let cartData = this.state.cartData;
            let C_GoodsIds = []
            let appoitgoods = []
            if(cartData){ // 预约商品列表
                cartData.cartList.map((item) => {
                    C_GoodsIds.push(item.ID)
                    appoitgoods.push({
                        N_GoodsId: item.ID,
                        N_Num: item.num
                    })
                })
                C_GoodsIds = C_GoodsIds.join(',')
            }
            this.setState({
                C_GoodsIds,
                appoitgoods
            })
        }
        
    }
    // 设置数据
    loadData(data){
        let userInfo = data ? data : Taro.getStorageSync('userInfo')
        let artificerItem = this.$router.params.artificerItem ? JSON.parse(this.$router.params.artificerItem) : null;
        let cartData = null;
        if(this.$router.params.cartData ){
            cartData =JSON.parse(this.$router.params.cartData)
        }
        let C_GoodsIds = []
        let appoitgoods = []
        let C_MebName = null
        if(cartData){ // 预约商品列表
            cartData.cartList.map((item) => {
                C_GoodsIds.push(item.ID)
                appoitgoods.push({
                    N_GoodsId: item.ID,
                    N_Num: item.num
                })
            })
            C_GoodsIds = C_GoodsIds.join(',')
        }
        if(userInfo){
            C_MebName = userInfo.C_MB_NICKNAME != '' ? userInfo.C_MB_NICKNAME : userInfo.C_MB_NAME
        }
        
        this.setState({
            cartList: cartData ? cartData.cartList : null,
            orderTotal: cartData ? cartData.price.orderTotal : null,
            peopleNum: this.$router.params.peopleNum || 0,
            userInfo,
            C_ApptMebNo: userInfo ? userInfo.C_MB_NO : '',
            C_GoodsIds: C_GoodsIds.length > 0 ? C_GoodsIds : '', //预约商品编号
            C_MebCardNo: userInfo ? userInfo.C_CARD_NO : '',
            C_MebName: C_MebName || '',
            C_MebPhone: userInfo ? userInfo.C_MB_PHONE : '',
            appoitgoods,
            artificerItem,
            D_StartDate: this.$router.params.D_StartDate || '',
            D_EndDate: this.$router.params.D_EndDate || '',
            C_AddDate: this.$router.params.C_AddDate || '',
            N_StaffId: artificerItem ? artificerItem.n_ss_id : 0,
            checkboxItems: [
                {name: '到店选择', value: '0', checked: true},
                {name: '预定项目', value: '1', checked: false}
            ],
            checkboxIndex: 0,
        },() => {
            this.setState({
                ItemInputData: [
                    {'label': '您的姓名','type': 'text','placeholder': '请填写您的姓名', 'names': 'C_MebName','value': this.state.C_MebName},
                    {'label': '联系方式','type': 'number','placeholder': '请填写您的电话号码', 'names': 'C_MebPhone','value': this.state.C_MebPhone},
                    {'label': '消费人数','type': 'number','placeholder': '请填写本次消费的人数', 'names': 'N_CustomerNum','value': this.state.peopleNum ? this.state.peopleNum : ''}
                ]
            })
        })
    }
   
    // 点击支付宝登陆后
    setUserInfo(userInfo){
        this.loadData(userInfo)
    }
    // 备注
    bindinput(val,name){
        if(name == 'name'){
            this.state.C_MebName = val
        }else if(name == 'phone'){
            this.state.C_MebPhone = val
        }else{
            this.state.C_Remark = val
        }
        this.setState({
            C_MebName: this.state.C_MebName,
            C_MebPhone: this.state.C_MebPhone,
            C_Remark: this.state.C_Remark,
        })
    }
    // 为空提示
    tipsTxt(){
        this.state.submitState = true
        let txt = ''
        if(this.state.C_MebName == ''){
            txt = '联系人不能为空'
        }else if(this.state.C_MebPhone == ''){
            txt = '手机号不能为空'
        }else if(this.state.peopleNum == 0){
            txt = '预约人数不能为0'
        }else if(this.state.D_StartDate == ''){
            txt = '请选择到店时间'
        }else{
            this.state.submitState = false
        }
        if(this.state.submitState){
            base.showModal(txt)
        }
    }
    // 加载状态
    loadingState(s){
        if(s){
            base.showLoading()
            this.state.submitState = true
        }else{
            this.state.submitState = false
            Taro.hideLoading()
        }
    }
    // 切换预定项目
    onChange(e){
        let checkboxIndex = e.type ? e.detail.value : e
        this.setState({
            checkboxIndex
        })
    }
    // 确认下单
    submitOrder(){
        let {industry} = this.state
        this.tipsTxt()
        if(this.state.submitState){return}
        this.loadingState(true)
        this.submitLs(industry)
    }
    // 美业、零售预约
    submitLs(industry){
        const {checkboxIndex} = this.state
        let appoitdetail = {
            C_AddDate: this.state.C_AddDate,
            C_ApptMebNo: this.state.C_ApptMebNo,
            C_GoodsIds: this.state.C_GoodsIds,
            C_MebCardNo: this.state.C_MebCardNo,
            C_MebName: this.state.C_MebName,
            C_MebPhone: this.state.C_MebPhone,
            C_Remark: this.state.C_Remark,
            C_Shop_No: getGlobalData('SHOP_NO'),
            D_EndDate: this.state.D_EndDate,
            D_StartDate: this.state.D_StartDate,
            N_ApptType: this.state.N_ApptType,
            N_CustomerNum: this.state.peopleNum,
            N_Id: this.state.N_Id,
            N_OpId: this.state.N_OpId,
            N_StaffId: this.state.N_StaffId
        }
        const str = `appoitdetail&appoitgoods&ShopNo`
        let params = {
            appoitdetail: JSON.stringify(appoitdetail),
            appoitgoods: JSON.stringify(this.state.appoitgoods) 
        }
        // 316餐饮1  2626零售2  390美业3
        if(industry == 390){
            params.bNo = 5002
            if(this.state.subscribeProject){
                this.state.subscribeProject.map((item) => {
                    delete item.GOODS_NAME
                })
                console.log('this.state.subscribeProject------------')
                console.log(this.state.subscribeProject)
            }
            params.appoitgoods = checkboxIndex == 0 ? [] : JSON.stringify(this.state.subscribeProject) 
        }else if(industry == 2626){
            params.bNo = 5011
            params.appoitgoods = checkboxIndex ? JSON.stringify(this.state.appoitgoods) : []
        }
        api.post(str,params).then((res) => {
            if(res.Result == '0'){
                base.showModal('预约失败，请重试！')
            }else if(res.Result == '2'){
                base.showModal('预约时间无效，请重新选择！',null,() => {
                    Taro.navigateTo({
                        url: '/pages/subscribeDate/index'
                    })
                })
            }else if(res.Result == '1'){
                setGlobalData('cartData', null) 
                base.showModal('预约成功', null, () => {
                    Taro.redirectTo({ url: '/pages/subscribeList/index' })
                })
            }
            this.loadingState()
        }).catch((err) => {
            base.showModal(err.msg)
            this.loadingState()
        })
    }
    // input 输入框
    onInput(names,e){
        const value = e.detail.value 
        if(names == 'C_MebName'){
            this.state.C_MebName = value
        }else if(names == 'C_MebPhone'){
            this.state.C_MebPhone = value
        }else if(names == 'N_CustomerNum'){
            this.state.peopleNum = value
        }
        console.log(this.state.C_MebName,this.state.C_MebPhone,this.state.peopleNum)
        this.setState({
            C_MebName: this.state.C_MebName,
            C_MebPhone: this.state.C_MebPhone,
            peopleNum: this.state.peopleNum,
        })
    }

    

    render() {
        let {industry,cartList,C_MebName,C_MebPhone,peopleNum,D_StartDate,C_Remark,orderTotal,checkboxItems,checkboxIndex,subscribeProject} = this.state
        return (
            <View className='main-subscribeSubmit'>
                {/* 零售 */}
                {industry == 2626 && <View>
                    <Good title='预约商品' cartList={cartList}></Good>
                    <Info title='订单信息' C_MebName={C_MebName} C_MebPhone={C_MebPhone} peopleNum={peopleNum} D_StartDate={D_StartDate} onInput={this.bindinput.bind(this)}></Info>
                    <Remark title='整单备注' C_Remark={C_Remark} onInput={this.bindinput.bind(this)}></Remark>
                    <Footer orderTotal={orderTotal} onSubmitOrder={this.submitOrder.bind(this)}></Footer>
                </View>}
                {/* 美业 */}
                {industry == 390 && <View className='industry${industry}'>
                    <View className='weui-cells weui-cells-none'>
                        {this.state.ItemInputData.map((item,i) => (
                            <View className={i > 0 ? 'border-top' : ''} key={'ItemInputData' + i}>
                                <ItemInput label={item.label} type={item.type} placeholder={item.placeholder} onInput={this.onInput.bind(this, item.names)} value={item.value} ></ItemInput>
                            </View>
                        ))}
                    </View>
                    <View className='weui-cells weui-cells-none'>
                        <View class={`weui-cell weui-cell-${process.env.TARO_ENV}`}>
                            <View class="weui-cell__hd">
                                <View class="weui-label">到店时间</View>
                            </View>
                            <View class="weui-cell__bd">
                                <View className='text-input'>{D_StartDate}</View>
                            </View>
                        </View>
                        <View class={`weui-cell weui-cell-${process.env.TARO_ENV}`}>
                            <View class="weui-cell__hd">
                                <View class="weui-label">预定项目</View>
                            </View>
                            <View class="weui-cell__bd">
                                <RadioGroup onChange={this.onChange}>
                                    {checkboxItems.map((item, i) => (
                                        <Label className='radio-list__label mr20' key={i}>
                                            <Radio className='radio-list__radio' value={item.value} checked={item.checked}></Radio>
                                            <Text className='text-input'>{item.name}</Text>
                                        </Label>
                                    ))}
                                </RadioGroup>
                            </View>
                        </View>
                        {checkboxIndex && checkboxIndex == 1 &&
                            <Navigator class="weui-cell" url='/pages/subscribeProject/index'>
                                <View class="weui-cell__hd">
                                    <View class="weui-label">{subscribeProject ? '已选项目' : '选择项目'}</View>
                                </View>
                                <View class="weui-cell__bd">
                                    {subscribeProject ? 
                                        <View>
                                            {subscribeProject.map((item,i) => (
                                                <View key={'subscribeProject' + i} className='weui-flex'>
                                                    <View className='weui-flex__item ellipsis'>{item.GOODS_NAME}</View>
                                                    <View className='ml20 text-gray'>×{item.N_Num}</View>
                                                </View>
                                            ))}
                                        </View> : 
                                        <View className='text-placeholder text-input'>请选择预定项目</View>
                                    }
                                </View>
                                <View class="weui-cell__ft weui-cell__ft_in-access"></View>
                            </Navigator>
                        }
                    </View>
                    <View className='p20'>
                        <Button className='btn-main' onClick={this.submitOrder}>确定预定</Button>
                    </View>
                </View>}
                {/* 登陆 */}
                <Authorize page='onSetUserInfo' onSetUserInfo={this.getIsLogin.bind(this)}></Authorize>
            </View>
        )
    }
}

